package org.chen.wordwave.act.game;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.toast.Toaster;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.base.ui.LuckyView;
import org.chen.wordwave.bean.SignIn;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.tools.user.UserUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Lucky extends BaseActivity {
    private TextView tvUsername, tvLotteryCount, tvPoints, tvPrizeInfo,tv_discountCoupon,tv_title;
    private Button btnConfirm, btnRules;
    private LuckyView ldView;
    private UserInfo currentUser;
    private ApiService apiService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        apiService = ApiClient.getClient(this).create(ApiService.class);
    }

    @Override
    public Integer getLayoutResId() {
        return R.layout.lucky_gift;
    }

    @SuppressLint("ObsoleteSdkInt")
    @Override
    public void init() {
        tvUsername = findViewById(R.id.tv_username);
        tvLotteryCount = findViewById(R.id.tv_lottery_count);
        tvPoints = findViewById(R.id.tv_points);
        tvPrizeInfo = findViewById(R.id.tv_prize_info);
        btnConfirm = findViewById(R.id.btn_confirm);
        btnRules = findViewById(R.id.btn_rules);
        ldView = findViewById(R.id.ldcv_bottom);
        tv_discountCoupon = findViewById(R.id.tv_discountCoupon);
        tv_title = findViewById(R.id.tv_title);

        // 标题文本和动画设置
        tv_title.setSelected(true);
        tv_title.setFocusable(true);
        tv_title.setFocusableInTouchMode(true);
        tv_title.requestFocus();

        // 处理系统状态栏，确保标题不被遮挡
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }

        currentUser = UserUtils.getCurrentUser(getApplicationContext());
        updateUserInfo();

        // 简化回调逻辑，移除复杂的标志位
        ldView.setDrawListener(new LuckyView.DrawListener() {
            @Override
            public void onDrawComplete(String prize) {
                // 添加调试日志
                android.util.Log.d("Lucky", "onDrawComplete called with prize: " + prize);
                handlePrize(prize);
            }

            @Override
            public int getUserLotteryCount() {
                int count = currentUser.getLuckyDrawBtn();
                android.util.Log.d("Lucky", "getUserLotteryCount: " + count);
                return count;
            }
        });

        btnConfirm.setOnClickListener(v -> finish());
        btnRules.setOnClickListener(v -> showRulesDialog());
    }

    @SuppressLint("SetTextI18n")
    private void updateUserInfo() {
        if (currentUser == null) {
            android.util.Log.e("Lucky", "currentUser is null in updateUserInfo");
            return;
        }

        tvUsername.setText(getString(R.string.username_lucky) + currentUser.getAccount());
        tvLotteryCount.setText(getString(R.string.count_lucky) + currentUser.getLuckyDrawBtn());
        tvPoints.setText(getString(R.string.jifen_lucky) + currentUser.getPoints());
        tv_discountCoupon.setText(getString(R.string.zhekou_lucky) + (currentUser.isHasDiscountCoupon() ? currentUser.getDiscountRate() * 100 + "%" : getString(R.string.non_discount)));
    }

    @SuppressLint("SetTextI18n")
    private void handlePrize(String prize) {
        android.util.Log.d("Lucky", "handlePrize called with: " + prize);

        if (prize == null || prize.isEmpty()) {
            android.util.Log.e("Lucky", "Prize is null or empty");
            return;
        }

        // 检查抽奖次数
        if (currentUser.getLuckyDrawBtn() <= 0) {
            android.util.Log.w("Lucky", "No lottery chances left");
            Toaster.show("抽奖次数已用完");
            return;
        }

        tvPrizeInfo.setText(getString(R.string.win) + prize + getString(R.string.wins));
        tvPrizeInfo.setVisibility(View.VISIBLE);

        // 记录原始数据
        int originalPoints = currentUser.getPoints();
        int originalLuckyDrawBtn = currentUser.getLuckyDrawBtn();
        boolean originalHasDiscountCoupon = currentUser.isHasDiscountCoupon();
        double originalDiscountRate = currentUser.getDiscountRate();

        android.util.Log.d("Lucky", "Original data - Points: " + originalPoints + ", LuckyDraw: " + originalLuckyDrawBtn);

        // 处理奖品逻辑
        boolean wonSomething = false;

        if (prize.equals(getString(R.string.points_10))) {
            currentUser.setPoints(currentUser.getPoints() + 10);
            wonSomething = true;
            android.util.Log.d("Lucky", "Won 10 points");
        } else if (prize.equals(getString(R.string.points_50))) {
            currentUser.setPoints(currentUser.getPoints() + 50);
            wonSomething = true;
            android.util.Log.d("Lucky", "Won 50 points");
        } else if (prize.equals(getString(R.string.points_100))) {
            currentUser.setPoints(currentUser.getPoints() + 100);
            wonSomething = true;
            android.util.Log.d("Lucky", "Won 100 points");
        } else if (prize.equals(getString(R.string.discount_20))) {
            currentUser.setHasDiscountCoupon(true);
            currentUser.setDiscountRate(0.8);
            wonSomething = true;
            android.util.Log.d("Lucky", "Won discount coupon");
        } else if (prize.equals(getString(R.string.points_200))) {
            currentUser.setPoints(currentUser.getPoints() + 200);
            wonSomething = true;
            android.util.Log.d("Lucky", "Won 200 points");
        } else if (prize.equals(getString(R.string.points_300))) {
            currentUser.setPoints(currentUser.getPoints() + 300);
            wonSomething = true;
            android.util.Log.d("Lucky", "Won 300 points");
        } else {
            android.util.Log.d("Lucky", "No prize won");
        }

        // 减少抽奖次数
        currentUser.setLuckyDrawBtn(currentUser.getLuckyDrawBtn() - 1);
        android.util.Log.d("Lucky", "Reduced lottery count to: " + currentUser.getLuckyDrawBtn());

        // 如果没中奖，只需要减少抽奖次数
        if (!wonSomething) {
            currentUser.save();
            updateUserInfo();
            Toaster.show(R.string.thanks_for_participating);
            return;
        }

        // 中奖了，保存数据并更新UI
        currentUser.save();
        updateUserInfo();

        android.util.Log.d("Lucky", "Updated data - Points: " + currentUser.getPoints() + ", LuckyDraw: " + currentUser.getLuckyDrawBtn());

        // 准备网络请求
        SignIn signIn = new SignIn();
        signIn.setEmail(currentUser.getEmail());
        signIn.setPoints(currentUser.getPoints());
        signIn.setHasDiscountCoupon(currentUser.isHasDiscountCoupon());
        signIn.setDiscountRate(currentUser.getDiscountRate());
        signIn.setLuckyDrawBtn(currentUser.getLuckyDrawBtn());
        signIn.setMember(currentUser.isMember());

        android.util.Log.d("Lucky", "Sending network request...");

        // 发送网络请求
        new Thread(() -> {
            apiService.gift(signIn).enqueue(new Callback<SignIn>() {
                @Override
                public void onResponse(@NonNull Call<SignIn> call, @NonNull Response<SignIn> response) {
                    android.util.Log.d("Lucky", "Network response received");
                    runOnUiThread(() -> {
                        if (response.isSuccessful() && response.body() != null) {
                            android.util.Log.d("Lucky", "Network request successful");
                            // 网络成功，但不覆盖本地数据
                            // 可以在这里添加成功提示
                        } else {
                            android.util.Log.e("Lucky", "Network response failed: " + response.code());
                            // 网络失败，回滚数据
                            rollbackUserData(originalPoints, originalLuckyDrawBtn,
                                    originalHasDiscountCoupon, originalDiscountRate);
                            Toaster.show(R.string.network_error);
                        }
                    });
                }

                @Override
                public void onFailure(@NonNull Call<SignIn> call, @NonNull Throwable t) {
                    android.util.Log.e("Lucky", "Network request failed", t);
                    runOnUiThread(() -> {
                        // 网络失败，回滚数据
                        rollbackUserData(originalPoints, originalLuckyDrawBtn,
                                originalHasDiscountCoupon, originalDiscountRate);
                        Toaster.show(R.string.network_error);
                    });
                }
            });
        }).start();
    }

    private void rollbackUserData(int originalPoints, int originalLuckyDrawBtn,
                                  boolean originalHasDiscountCoupon, double originalDiscountRate) {
        android.util.Log.d("Lucky", "Rolling back user data");
        currentUser.setPoints(originalPoints);
        currentUser.setLuckyDrawBtn(originalLuckyDrawBtn);
        currentUser.setHasDiscountCoupon(originalHasDiscountCoupon);
        currentUser.setDiscountRate(originalDiscountRate);
        currentUser.save();
        updateUserInfo();
    }

    private void showRulesDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.lucky_info);
        String message = getString(R.string.lucky_info_content);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.yes, (dialog, id) -> dialog.dismiss());
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (tv_title != null) {
            tv_title.setSelected(true);
        }
        // 重新获取最新的用户数据
        currentUser = UserUtils.getCurrentUser(getApplicationContext());
        updateUserInfo();
    }
}